import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { IActivityProperty } from 'app/shared/model/activity-property.model';
import { ActivityPropertyAppender } from 'app/entities/activity-property/activity-property-appender';

export const ActivityPropertyContainer = forwardRef(({ properties }: any, ref: any) => {
  const listRef = useRef(null);
  const propRefs = useRef([]);
  const [renderData, setRenderData] = useState([]);

  useEffect(() => {
    if (properties) {
      setRenderData([...properties]);
    }
  }, [properties]);

  const addProperty = event => {
    const prop: IActivityProperty = {
      id: null,
      propertyName: null,
      propertyValue: null,
      propertyType: 'TEXT',
      propertyRemark: null,
      orderNo: null,
    };
    setRenderData([...renderData, prop]);
  };

  const deleteProperty = index => {
    setRenderData(renderData.filter((_, idx) => index != idx));
  };

  const changeProperty = (index, content) => {
    const list = renderData.map((p, idx) => {
      if (idx == index) {
        const copy = { ...p };
        if (content.name) {
          copy.propertyName = content.name;
        } else {
          copy.propertyValue = content.value;
        }
        return copy;
      }
      return p;
    });
    setRenderData(list);
  };

  function getLatestProps() {
    const newProps = Array.from(listRef.current.children)
      .filter((e: any) => e.nodeName.toLowerCase() == 'div')
      .map((p: any, index) => {
        const id = p.querySelector('#data-id').value ? parseInt(p.querySelector('#data-id').value) : null;
        const newp = {
          id: id,
          propertyName: p.querySelector('#activity-property-name').value
            ? p.querySelector('#activity-property-name').value
            : p.querySelector('#activity-property-name').innerText,
          propertyValue: p.querySelector('#activity-property-value' + index).value,
        };
        return newp;
      });
    return newProps;
  }

  useImperativeHandle(ref, () => ({
    getLatestProps,
  }));

  return (
    <div ref={listRef}>
      {renderData
        ? renderData.map((property, index) => (
            <ActivityPropertyAppender
              property={property}
              index={index}
              propRefs={propRefs}
              deletePropertyMethod={deleteProperty}
              changePropertyMethod={changeProperty}
              key={property.id ? property.id : Math.random()}
            />
          ))
        : null}
      <input onClick={addProperty} type="button" value="添加属性" />
    </div>
  );
});

export default ActivityPropertyContainer;
